﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Composite.Presentation.Regions;
using AvalonDock;
using Microsoft.Practices.Composite.Regions;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Regions.Behaviors;
using System.Windows.Controls.Primitives;
using System.Windows;
using OpenExpressApp.Event;
using System.Collections.Specialized;
using System.ComponentModel;
using OpenExpressApp.Template;
using System.Diagnostics;
using Avalon.Windows.Controls;

namespace OpenExpressApp
{
    /// <summary>
    /// 从IRegion适配到DocumentPane
    /// </summary>
    internal class DocumentPaneRegionAdapter : RegionAdapterBase<DocumentPane>
    {
        /// <summary>
        /// 全局事件集合器
        /// </summary>
        private IEventAggregator _eventAggregator;

        /// <summary>
        /// 适配到这个AvalonDockRegion对象
        /// </summary>
        private Region _region;

        /// <summary>
        /// 被适配的DocumentPane控件
        /// </summary>
        private DocumentPane _documentPane;

        /// <summary>
        /// 当前是否正在进行SelectView操作。
        /// 增加这个变量是因为防止SelectView方法的递归调用。
        /// </summary>
        private bool _selecting;

        public DocumentPaneRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory, IEventAggregator eventAggregator)
            : base(regionBehaviorFactory)
        {
            this._eventAggregator = eventAggregator;
        }

        protected override IRegion CreateRegion()
        {
            this._region = new SingleActiveRegion();
            return this._region;
        }

        protected override void Adapt(IRegion region, DocumentPane regionTarget)
        {
            this._region.ActiveViews.CollectionChanged += RegionActiveViews_CollectionChanged;
            this._region.Views.CollectionChanged += RegionViews_CollectionChanged;

            this._documentPane = regionTarget;
            this._documentPane.SelectionChanged += new SelectionChangedEventHandler(DocumentPane_SelectionChanged);
        }

        /// <summary>
        /// 在选择控件时，激活View
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DocumentPane_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var docContent = e.AddedItems[0] as DocumentContent;
                if (docContent != null)
                {
                    foreach (Control view in LogicalTreeHelper.GetChildren(docContent))
                    {
                        this.SelectView(view);
                        break;
                    }
                }
            }
        }

        private void RegionActiveViews_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (this._documentPane != null)
            {
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        this.OnRegionActiveViewAdded(e);
                        break;
                    default:
                        break;
                }
            }
        }

        private void RegionViews_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (this._documentPane != null)
            {
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        this.OnRegionViewAdded(e);
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        this.OnRegionViewRemoved(e);
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// 在激活某个View时，把它的DocumentContent选中。
        /// </summary>
        /// <param name="e"></param>
        private void OnRegionActiveViewAdded(NotifyCollectionChangedEventArgs e)
        {
            var view = e.NewItems[0] as Control;

            this.SelectView(view);
        }

        /// <summary>
        /// 如果是添加了View进来，则生成所有View的控件
        /// </summary>
        private void OnRegionViewAdded(NotifyCollectionChangedEventArgs e)
        {
            DocumentContent content = null;

            //对应每一个加入的View，生成具体的DocumentContent控件。
            //这里假定所有的view都是Control类型。否则不起作用
            foreach (var control in e.NewItems.OfType<Control>())
            {
                Debug.Assert(control is IWindowTemplate, "view 必须实现了IWindowTemplate接口。");

                //找到viewControl原来的父节点DocumentContent，然后去除他们间的父子关系
                content = LogicalTreeHelper.GetParent(control) as DocumentContent;
                if (content != null)
                {
                    content.Content = null;
                }

                //构造一个新的DocumentContent
                content = new DocumentContent()
                {
                    Content = control,
                    Title = (control as IWindowTemplate).Title
                };
                content.Closing += DocumentContent_Closing;
                content.Closed += DocumentContent_Closed;

                this._documentPane.Items.Add(content);
            }
        }

        /// <summary>
        /// 删除View时，则直接把它从逻辑树中移除。
        /// </summary>
        /// <param name="e"></param>
        private void OnRegionViewRemoved(NotifyCollectionChangedEventArgs e)
        {
            foreach (Control item in e.OldItems)
            {
                //找到并移除对应的DocumentContent
                foreach (DocumentContent content in this._documentPane.Items)
                {
                    if (content.Content == item)
                    {
                        this._documentPane.Items.Remove(content);
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 在DocumentContent关闭时，发送关闭事件到EventAggregator。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DocumentContent_Closing(object sender, CancelEventArgs e)
        {
            var result = TaskDialog.Show("是否关闭模块?", "确认关闭", TaskDialogButtons.Yes | TaskDialogButtons.No);

            if (result.ButtonData == null || result.ButtonData.Button != TaskDialogButtons.Yes)
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 通知总线全局关闭模块事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DocumentContent_Closed(object sender, EventArgs e)
        {
            var eventObj = this._eventAggregator.GetEvent<ObjectModuleClosedEvent>();
            eventObj.Publish((sender as DocumentContent).Content as Control);
        }

        /// <summary>
        /// 选中指定的View
        /// </summary>
        /// <param name="view"></param>
        private void SelectView(Control view)
        {
            if (view != null)
            {
                if (this._selecting == false)
                {
                    this._selecting = true;

                    try
                    {
                        //激活View
                        this._region.Activate(view);

                        //选中控件
                        var content = LogicalTreeHelper.GetParent(view) as DocumentContent;
                        this._documentPane.SelectedValue = content;
                    }
                    finally
                    {
                        this._selecting = false;
                    }
                }
            }
        }
    }

    //internal class DockablePaneRegionAdapter : RegionAdapterBase<DockablePane>
    //{
    //    public DockablePaneRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
    //        : base(regionBehaviorFactory) { }

    //    protected override IRegion CreateRegion()
    //    {
    //        return new AllActiveRegion();
    //    }

    //    protected override void Adapt(IRegion region, DockablePane regionTarget)
    //    {
    //        //暂时没用到

    //        //region.ActiveViews.CollectionChanged += (s, e) =>
    //        //{
    //        //    var childs = new Dictionary<object, DockableContent>();
    //        //    foreach (var child in regionTarget.Items)
    //        //    {
    //        //        var content = child as DockableContent;
    //        //        if (content != null)
    //        //        {
    //        //            childs.Add(content.Content, content);
    //        //        }
    //        //    }
    //        //    regionTarget.Items.Clear();
    //        //    foreach (object ci in region.Views)
    //        //    {
    //        //        DockableContent dc = childs.ContainsKey(ci)
    //        //            ? childs[ci]
    //        //            : new DockableContent() { Content = ci };
    //        //        dc.Title = (string)((Control)ci).GetValue(Window.TitleProperty);
    //        //        regionTarget.Items.Add(dc);
    //        //    }
    //        //};
    //    }
    //}
}